#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import zipfile
import socket
import commands
from datetime import date,datetime,timedelta

########指定配置文件目录#########
backup_dir='/data/backup'   #本地的备份目录（即要把备份文件放在哪里）
mysql_user='root'    #mysql用户名
mysql_password='%2ab%$3k?to'   #mysql密码
print("checking backup directory...")
try:
    if os.path.isdir(backup_dir):
        print("found backup directory " + backup_dir + ", ready to process backup...")
    else:
        print("don't found backup directory " + backup_dir + ", try to build one...")
        os.mkdir(backup_dir)
except IOError, err:
    print err
    sys.exit()

newday = date.today()    #获取今天的日期
oldday = date.today()-timedelta(91155)    #获得91155天前的日期

gamedb= backup_dir + '/' + 'gamedb_' + str(newday.year) + '.' + str(newday.month) + '.' +  str(newday.day) + '.sql.gz'    #本次导出的数据库名

print("today is " + str(newday.year) + "." + str(newday.month) + "." +  str(newday.day))



print("export your databases...")    #导出数据库
try:
    cmd1 = "mysqldump -u" + mysql_user + " -p'" + mysql_password + "' gamedb | gzip > " + gamedb
    h = commands.getstatusoutput(cmd1)
    if h[0] == 0:
        print("export databases successful, continue processing...")
    else:
        print("export databases failed. please check your mysql username or password, or check mysql server status.")
        sys.exit()
except IOError, error:
    print error
    sys.exit()
print "backup is ok"
